package com.qinglei.recoup.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.qinglei.recoup.common.domain.CommonRes;
import com.qinglei.recoup.common.utils.DateUtil;
import com.qinglei.recoup.common.utils.RecoupUtil;
import com.qinglei.recoup.system.dao.*;
import com.qinglei.recoup.system.domain.*;
import com.qinglei.recoup.system.domain.vo.DeanRotationVo;
import com.qinglei.recoup.system.domain.vo.RadarBedVo;
import com.qinglei.recoup.system.enums.EventEnum;
import com.qinglei.recoup.system.enums.RoleEnum;
import com.qinglei.recoup.system.pojo.BedMonitorTimeVO;
import com.qinglei.recoup.system.pojo.HealthStatusComment;
import com.qinglei.recoup.system.pojo.HealthStatusCommentVO;
import com.qinglei.recoup.system.service.BedMonitorTimeService;
import com.qinglei.recoup.system.service.DeanDataService;
import com.qinglei.recoup.system.service.RadarBedService;
import com.qinglei.recoup.system.service.RadarService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.omg.PortableInterceptor.INACTIVE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class DeanDataServiceImpl extends ServiceImpl<TBedHealthDailyStatisticsDataMapper, TBedHealthDailyStatisticsData> implements DeanDataService {

    @Resource
    private TBedHealthDailyStatisticsDataMapper tBedHealthDailyStatisticsDataMapper;

    @Resource
    private DeanBedMapper deanBedMapper;

    @Resource
    private BedServiceImpl bedService;
    @Resource
    private EventMapper eventMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private NurseBedMapper nurseBedMapper;
    @Resource
    private NurseStatisticsMapper nurseStatisticsMapper;
    @Resource
    private NurseOnlineMapper nurseOnlineMapper;
    @Resource
    private MonitorTimeMapper monitorTimeMapper;
    @Resource
    private EventProcMapper eventProcMapper;

    @Resource
    private BedMonitorTimeService bedMonitorTimeService;

    @Resource
    private BedHealthDailyStatisticsMapper bedHealthDailyStatisticsMapper;
    @Resource
    private RadarBedService radarBedService;

    @Override
    public Map getTopList() {
        LocalDate localDate = LocalDate.now().minusDays(1);
        List<Integer> deanAllUser = getBeanAllByUser(RecoupUtil.getCurrentUser(), null, null);
        System.err.println(deanAllUser);
        //根据床位ID查询雷达设备号
        Map<Integer, RadarBedVo> radarBedMapByBedIds = radarBedService.getRadarBedMapByBedIds(deanAllUser);

        Map result = new HashMap<>();
        result.put("sleepTop", getSleepTopList(localDate, deanAllUser, "score",radarBedMapByBedIds));
        result.put("ahiTop", getAhiTopList(localDate, deanAllUser, "ahi",radarBedMapByBedIds));
        List fallList = getFallTopList(localDate, deanAllUser, "fall_index",radarBedMapByBedIds);

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("statistics_date",localDate);
        queryWrapper.in("bed_id",deanAllUser);
        Integer healthyReportNum = bedHealthDailyStatisticsMapper.selectCount(queryWrapper);
        Map<String,Integer> resultReason = new HashMap<>();
        if(fallList==null ||fallList.size()==0){
            if(healthyReportNum==0){
                resultReason.put("fallReason",1);
            }else {
                resultReason.put("fallReason",2);
            }
        }else{


            resultReason.put("fallReason",0);
            result.put("fallTop",fallList);
        }

        List moraleTop =  getMoraleTopList(localDate, deanAllUser, "morale_index",radarBedMapByBedIds);
        if(moraleTop==null ||moraleTop.size()==0){
            if(healthyReportNum==0){
                resultReason.put("moraleReason",1);
            }else {
                resultReason.put("moraleReason",2);
            }
        }else{
            resultReason.put("moraleReason",0);
            result.put("moraleTop",moraleTop);
        }


        List vitalityTop = getVitalityTopList(localDate, deanAllUser, "vitality_index",radarBedMapByBedIds);

        if(vitalityTop==null ||vitalityTop.size()==0){
            if(healthyReportNum==0){
                resultReason.put("vitalityReason",1);
            }else {
                resultReason.put("vitalityReason",2);
            }
        }else{
           resultReason.put("vitalityReason",0);
            result.put("vitalityTop",vitalityTop);
        }

        result.put("resultReason",resultReason);
        return result;
    }

    @Override
    public Map<String, Object> getRotationTopList(DeanRotationVo vo) {
        Map<String, Object> result = new HashMap<>();
        if (StringUtils.isEmpty(vo.getQueryDate())) {
            vo.setQueryDate(LocalDate.now().minusDays(1).toString());
        }

        vo.setDeanIds(getBeanAllByUser(RecoupUtil.getCurrentUser(), null, null));
//        if (vo.getPageNum() != null) {
//            vo.setPageNum((vo.getPageNum() - 1) * vo.getPageSize());
//        }
        Integer count = tBedHealthDailyStatisticsDataMapper.getRotationTopListCount(vo);
        System.err.println(vo.getDeanIds());
        List<TBedHealthDailyStatisticsData> list = tBedHealthDailyStatisticsDataMapper.getRotationTopList(vo);
        List<Integer> bedIds = list.stream().map(TBedHealthDailyStatisticsData::getBedId).collect(Collectors.toList());
        Map<Integer, RadarBedVo> radarBedMapByBedIds = radarBedService.getRadarBedMapByBedIds(bedIds);
        list.forEach(t -> {
            t.setBedName(bedService.getBedName(t.getBedId()));
            if (StringUtils.isEmpty(vo.getOrderType()) || !vo.getOrderType().equals("desc")) {
                HealthStatusCommentVO v = new HealthStatusCommentVO();
                v.setSleepDuration(t.getScore().intValue());
                System.err.println(t);
                v.setAHI(t.getAhi());
                v.setVitality(t.getVitalityIndex());
                v.setMorale(t.getMoraleIndex());
                v.setFall(t.getFallIndex());
                v.setOutBedDuration(t.getOutBedDuration());
                v.setOutBedNum(t.getOutBedNum());
                v.setTurnOverNum(t.getTurnOverNum());
                String negativeResult = HealthStatusComment.getCommentOne(v);
                if (!StringUtils.isEmpty(negativeResult)) {
                    t.setHealthStatusComment(negativeResult);
                }
            }
            t.setStatisticsDate(LocalDate.now().minusDays(2));
            TBedHealthDailyStatisticsData rb = tBedHealthDailyStatisticsDataMapper.getRotationByIdAndDate(t);
            if (rb != null) {
                if (t.getVitalityIndex() != null && t.getVitalityIndex() > 0) {
                    if (rb.getVitalityIndex() != null && rb.getVitalityIndex() > t.getVitalityIndex()) {
                        t.setVitalityIsRise(-1);
                    } else if (rb.getVitalityIndex() != null && rb.getVitalityIndex() < t.getVitalityIndex()) {
                        t.setVitalityIsRise(1);
                    } else {
                        t.setVitalityIsRise(0);
                    }
                } else {
                    t.setVitalityIsRise(0);
                }
                if (t.getMoraleIndex() != null && t.getMoraleIndex() > 0) {
                    if (rb.getMoraleIndex() != null && rb.getMoraleIndex() > t.getMoraleIndex()) {
                        t.setMoraleIsRise(-1);
                    } else if (rb.getMoraleIndex() != null && rb.getMoraleIndex() < t.getMoraleIndex()) {
                        t.setMoraleIsRise(1);
                    } else {
                        t.setMoraleIsRise(0);
                    }
                } else {
                    t.setMoraleIsRise(0);
                }
                if (t.getFallIndex() != null && t.getFallIndex() > 0) {
                    if (rb.getFallIndex() != null && rb.getFallIndex() > t.getFallIndex()) {
                        t.setFallIsRise(-1);
                    } else if (rb.getFallIndex() != null && rb.getFallIndex() < t.getFallIndex()) {
                        t.setFallIsRise(1);
                    } else {
                        t.setFallIsRise(0);
                    }
                } else {
                    t.setFallIsRise(0);
                }
            }
            if (t.getVitalityIndex() == null || t.getVitalityIndex() < 1) {
                t.setVitalityIndex(0);
            }
            if (t.getMoraleIndex() == null || t.getMoraleIndex() < 1) {
                t.setMoraleIndex(0);
            }
            if (t.getFallIndex() == null || t.getFallIndex() < 1) {
                t.setFallIndex(0);
            }
            if(radarBedMapByBedIds.containsKey(t.getBedId())){
                t.setSn(radarBedMapByBedIds.get(t.getBedId()).getSnCode());
            }
        });
        result.put("total", count);
        result.put("records", list);
        return result;
    }

    @Override
    public Map<String, Object> getWholeSleep(Integer queryType) {
        Map<String, Object> result = new HashMap<>();
        String startDate = null;
        String endDate = LocalDate.now().toString();
        //获取到当前时间内所有的床位
        List<Integer> beanAll = getBeanAllByUser(RecoupUtil.getCurrentUser(), null, null);
        //床位总数即为当前守护老人的数量
        result.put("bedCount", beanAll.size());
        Integer dayNum = 7;
        if (queryType == null) {
            startDate = LocalDate.now().minusDays(dayNum).toString();
            getWholeSleep(result, startDate, endDate, beanAll, dayNum);
        } else if (queryType == 0) {
            //7天
            startDate = LocalDate.now().minusDays(dayNum).toString();
            List<Integer> beanTemp = getBeanAllByUser(RecoupUtil.getCurrentUser(), null, endDate);
            result.put("beanTemp",beanTemp.size());
            getWholeSleep(result, startDate, endDate, beanAll, dayNum);
            //对比下一周期
            return getNextWholeSleepResultData(result, startDate, endDate, dayNum);
        } else if (queryType == 1) {
            dayNum = 30;
            //30天
            startDate = LocalDate.now().minusDays(dayNum).toString();
            List<Integer> beanTemp = getBeanAllByUser(RecoupUtil.getCurrentUser(), null, endDate);
            result.put("beanTemp",beanTemp.size());
            getWholeSleep(result, startDate, endDate, beanAll, dayNum);
            return getNextWholeSleepResultData(result, startDate, endDate, dayNum);
        }
        return result;
    }

    @Override
    public Map<String, Object> getGeneralSituation() {
        Map<String, Object> result = new HashMap<>();
        String startDate = LocalDate.now().minusDays(7).toString();
        String endDate = LocalDate.now().toString();
        //院长下全部床位
        List<Integer> bedsAllByUser = getBeanAllByUser(RecoupUtil.getCurrentUser(), null, null);
        System.err.println(bedsAllByUser);
        List<Integer> bedsAllByUserV1 = getBeanAllByUserV1(RecoupUtil.getCurrentUser(), null, null);
        System.err.println(bedsAllByUserV1);
        //院长下全部护工
        List<Integer> nursesByUser = nurseBedMapper.getUserIdsByBedId(bedsAllByUser);


        //objectQueryWrapper.ne("type", 3);
        //累计报警
        QueryWrapper<Event> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.in("bed_id", bedsAllByUser);
        List<Integer> eventypes = new ArrayList<>();
        eventypes.add(1);
        eventypes.add(2);
        eventypes.add(4);
        eventypes.add(5);
        eventypes.add(7);
        eventypes.add(8);
        objectQueryWrapper.in("type",eventypes);
        Integer count = eventMapper.selectCount(objectQueryWrapper);
        result.put("warning", count);
        //及时处理
        Integer finishCount = nurseStatisticsMapper.selectEventFinishCount(nursesByUser);

        result.put("warningFinish", finishCount);
        //设备总数
        result.put("equipmentCount", bedsAllByUserV1.size());
        NurseOnline no = nurseOnlineMapper.selectOnline(nursesByUser);
        //总在线设备数
        double onlineBeds = 0;
        Integer curTime = 0;
        Integer notCurTime = 0;
        for (int i = 0; i < bedsAllByUserV1.size(); i++) {
            Integer bedId = bedsAllByUserV1.get(i);
            Bed bed = bedService.getBedWithSn(bedId);
            if (bed.getIsRadarOnline() == 1) {
                onlineBeds++;
                BedMonitorTimeVO bedMonitorTimeVO = bedService.getBedCurMonitorTime(bed.getId());
                if (bedMonitorTimeVO == null) {
                    bedMonitorTimeVO = bedMonitorTimeService.getNextMonitorTime(bed.getId());
                }
                LocalTime nowTime = LocalTime.now();
                LocalTime stratTime = LocalTime.parse(bedMonitorTimeVO.getStartTime());
                LocalTime endTime = LocalTime.parse(bedMonitorTimeVO.getEndTime());
                boolean inStart = nowTime.isAfter(stratTime);
                boolean inEnd = nowTime.isBefore(endTime);
                if (inStart && inEnd) {
                    curTime++;
                } else {
                    notCurTime++;
                }
            }

        }
        result.put("onlinePercent", Math.floor(onlineBeds * 100 / bedsAllByUserV1.size()));
        result.put("offlineCount", bedsAllByUserV1.size() - onlineBeds);

        LocalDate date = nurseOnlineMapper.selectMinDateByUserIds(nursesByUser);
        List<String> betweenDate = DateUtil.getBetweenDate(date.toString(), LocalDate.now().toString());
        //守护天数
        result.put("dayNum", betweenDate.size());
        result.put("curTime", curTime);
        result.put("notCurTime", notCurTime);

        //当天报警总数
        int alermCountDay = 0;
        List<EventProc> procList = eventProcMapper.getCountByBedIds(bedsAllByUser);
        for (EventProc ev : procList) {
            switch (ev.getStatus()) {
                case 1:
                    alermCountDay += ev.getCount();
                    // result.put("untreated", ev.getCount());
                    break;
                case 2:
                    alermCountDay += ev.getCount();
                    result.put("processing", ev.getCount());
                    break;
                case 3:
                    alermCountDay += ev.getCount();
                    result.put("complete", ev.getCount());
                    break;
                case 4:
                    alermCountDay += ev.getCount();
                    break;
            }
        }
        result.put("untreated", alermCountDay);

        if (result.get("processing") == null) {
            result.put("processing", 0);
        }
        if (result.get("complete") == null) {
            result.put("complete", 0);
        }


        Iterator<Integer> iterator = nursesByUser.iterator();
        while (iterator.hasNext()) {
            User user = userMapper.selectByIdAndDate(iterator.next(), startDate, endDate);
            if (user == null) {
                iterator.remove();
            }
        }
        NurseStatistics nurseStatistics = nurseStatisticsMapper.selectDataByDate(nursesByUser, startDate, endDate);
        if (nurseStatistics != null) {
            nurseStatistics.setWorkTimeStr(DateUtil.getTimes(nurseStatistics.getWorkTime()));
            nurseStatistics.setUserCount(nursesByUser.size());
            result.put("leftData", nurseStatistics);
        } else {
            NurseStatistics nurseStatisticsEmpty = new NurseStatistics();
            nurseStatisticsEmpty.setEventProcTime(0);
            nurseStatisticsEmpty.setEventWaitTime(0);
            nurseStatisticsEmpty.setUserCount(0);
            nurseStatisticsEmpty.setWorkTime(0);
            nurseStatisticsEmpty.setWorkTimeStr("未工作");
            result.put("leftData", nurseStatisticsEmpty);
        }
        return result;
    }


    public Map<String, Object> getNextWholeSleepResultData(Map<String, Object> result, String startDate, String endDate, int dayNum) {
        //获取近期床位个数
        Integer firstBedCount = (Integer) result.get("beanTemp");
        //获取近期睡眠分数中位数
        double firstSleepScore = (double) (result.get("sleepScore") == null ? 0.0 : result.get("sleepScore"));
        startDate = LocalDate.parse(startDate).minusDays(dayNum).toString();
        endDate = LocalDate.parse(endDate).minusDays(dayNum).toString();

        //获取 startDate, endDate 时间内的床位
        List<Integer> beanAllByUser = getBeanAllByUser(RecoupUtil.getCurrentUser(), null, endDate);
        Map<String, Object> stringObjectMap = getNextWholeSleep(startDate, endDate, beanAllByUser, dayNum);
        Integer nextBedCount = (Integer) (stringObjectMap.get("bedCount") == null ? 0 : stringObjectMap.get("bedCount"));
        double nextSleepScore = (double) (stringObjectMap.get("sleepScore") == null ? 0.0 : stringObjectMap.get("sleepScore"));
//        if (nextBedCount > 0) {
//            BigDecimal bigDecimal = new BigDecimal(nextBedCount).divide(new BigDecimal(firstBedCount), 2, BigDecimal.ROUND_DOWN).setScale(1, BigDecimal.ROUND_DOWN);
//            setSleepPercentageState(result, firstBedCount, nextBedCount, "bedCountPercentageState");
//            result.put("bedCountPercentage", bigDecimal);
//        } else {
//            result.put("bedCountPercentage", 0);
//            result.put("bedCountPercentageState", 0);
//        }

        if(firstBedCount>nextBedCount && nextBedCount!=0){
            BigDecimal bigDecimal = new BigDecimal(firstBedCount - nextBedCount).divide(new BigDecimal(nextBedCount),
                    3, BigDecimal.ROUND_DOWN).setScale(3, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100));
            result.put("bedCountPercentage", bigDecimal);
            result.put("bedCountPercentageState", 1);
        }else if(firstBedCount <nextBedCount && nextBedCount!=0){
            BigDecimal bigDecimal = new BigDecimal( nextBedCount -firstBedCount).divide(new BigDecimal(nextBedCount),
                    3, BigDecimal.ROUND_DOWN).setScale(3, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100));
            result.put("bedCountPercentage", bigDecimal);
            result.put("bedCountPercentageState", -1);
        }else {
            result.put("bedCountPercentage", 0);
            result.put("bedCountPercentageState", 0);
        }



        if(firstSleepScore>nextSleepScore && nextSleepScore!=0){
            BigDecimal bigDecimal = new BigDecimal(firstSleepScore - nextSleepScore).divide(new BigDecimal(nextSleepScore),
                    3, BigDecimal.ROUND_DOWN).setScale(3, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100));
            result.put("sleepPercentage", bigDecimal);
            result.put("sleepPercentageState", 1);
        }else if(firstSleepScore <nextSleepScore && nextSleepScore!=0){
            BigDecimal bigDecimal = new BigDecimal( nextSleepScore -firstSleepScore).divide(new BigDecimal(nextSleepScore),
                    3, BigDecimal.ROUND_DOWN).setScale(3, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100));
            result.put("sleepPercentage", bigDecimal);
            result.put("sleepPercentageState", -1);
        }else {
            result.put("sleepPercentage", 0);
            result.put("sleepPercentageState", 0);
        }
//        if (nextSleepScore > 0) {
//            BigDecimal bigDecimal = new BigDecimal(nextSleepScore).divide(new BigDecimal(firstSleepScore), 2, BigDecimal.ROUND_DOWN).setScale(1, BigDecimal.ROUND_DOWN);
//            setSleepPercentageState(result, firstSleepScore, nextSleepScore, "sleepPercentageState");
//            result.put("sleepPercentage", bigDecimal);
//        } else {
//            result.put("sleepPercentage", 0);
//            result.put("sleepPercentageState", 0);
//        }
        result.put("nextSleep", stringObjectMap.get("sleep"));
        result.put("nextBreathing", stringObjectMap.get("breathing"));
        result.put("nextWarning", stringObjectMap.get("warning"));
        return result;
    }

    public void setSleepPercentageState(Map<String, Object> result, double firstSleepScore, double nextSleepScore, String column) {
        if (nextSleepScore > firstSleepScore) {
            result.put(column, -1);
        } else if (nextSleepScore < firstSleepScore) {
            result.put(column, 1);
        } else {
            result.put(column, 0);
        }
    }

    public Map<String, Object> getNextWholeSleep(String startDate, String endDate, List<Integer> beanAllByUser, int day) {
        Map<String, Object> result = new HashMap<>();
        result.put("bedCount", beanAllByUser.size());
        TBedHealthDailyStatisticsData data = tBedHealthDailyStatisticsDataMapper.getBedCountNumber(startDate, endDate, beanAllByUser, day);
        if (data != null) {
            result.put("sleepScore", data.getScore());
        }
        Map<String, Integer> items = new HashMap<>();
        Map<String, Integer> breathing = new HashMap<>();
        breathing.put("low", 0);
        breathing.put("middle", 0);
        breathing.put("high", 0);
        List<TBedHealthDailyStatisticsData> list = tBedHealthDailyStatisticsDataMapper.getDataByBedIdAndDate(startDate, endDate, beanAllByUser);
        list.forEach(d -> {
            setSleepData(items, d);
            setBreathingData(breathing, d);
        });
        result.put("sleep", items);
        result.put("breathing", breathing);
        setWarningData(result, startDate, endDate, beanAllByUser);
        return result;
    }

    public void getWholeSleep(Map<String, Object> result, String startDate, String endDate, List<Integer> beanAllByUser, int day) {

        //获取startDate，endDate内睡眠平均睡眠分数，总睡眠分数，ahi、ai、hi平均分数
        TBedHealthDailyStatisticsData data = tBedHealthDailyStatisticsDataMapper.getBedCountNumber(startDate, endDate, beanAllByUser, day);
        //获取startDate，endDate内所有分数，升序排列
        List<Integer> sleepScoreS = tBedHealthDailyStatisticsDataMapper.getSleepScoreMedian(startDate, endDate, beanAllByUser);
        if (sleepScoreS != null && sleepScoreS.size() > 0) {
            int num = sleepScoreS.size();
            double sleepScore = 0;
            if (num % 2 == 0) {
                sleepScore = (sleepScoreS.get((sleepScoreS.size() / 2)) + sleepScoreS.get((sleepScoreS.size() / 2 + 1))) / 2;
            } else {
                sleepScore = sleepScoreS.get((sleepScoreS.size() - 1) / 2 + 1);
            }
            //睡眠分数中位数
            result.put("sleepScore", sleepScore);
        }
        Map<String, Integer> items = new HashMap<>();
        Map<String, Integer> breathing = new HashMap<>();
        breathing.put("low", 0);
        breathing.put("middle", 0);
        breathing.put("high", 0);
        //获取startDate，endDate内所有的睡眠数据
        List<TBedHealthDailyStatisticsData> list = tBedHealthDailyStatisticsDataMapper.getDataByBedIdAndDate(startDate, endDate, beanAllByUser);
        list.forEach(d -> {
            //统计睡眠分数段
            setSleepData(items, d);
            //统计呼吸慢病段
            setBreathingData(breathing, d);
        });
        result.put("sleep", items);
        result.put("breathing", breathing);
        //统计数据类型
        setWarningData(result, startDate, endDate, beanAllByUser);
    }


    public void setWarningData(Map<String, Object> result, String startDate, String endDate, List<Integer> beanAllByUser) {
        Map<String, Integer> warning = new HashMap<>();
        List<Event> events = eventMapper.selectByBedIds(startDate, endDate, beanAllByUser);
        events.forEach(e -> {
            switch (e.getType()) {
                case EventEnum.LEAVE_BED:
                    warning.put("leaveBed", e.getWarningCount());
                    break;
                case EventEnum.FALL:
                    warning.put("fall", e.getWarningCount());
                    break;
                case EventEnum.BREATHING_FAST:
                    warning.put("breathingFast", e.getWarningCount());
                    break;
                case EventEnum.BREATHING_STOP:
                    warning.put("breathingStop", e.getWarningCount());
                    break;
                case EventEnum.HEARTBEAT_FAST:
                    warning.put("heartbeatFast", e.getWarningCount());
                    break;
                case EventEnum.HEARTBEAT_SLOW:
                    warning.put("heartbeatSlow", e.getWarningCount());
                    break;
            }
        });
        if (warning.get("leaveBed") == null) {
            warning.put("leaveBed", 0);
        }
        if (warning.get("fall") == null) {
            warning.put("fall", 0);
        }
        if (warning.get("breathingFast") == null) {
            warning.put("breathingFast", 0);
        }
        if (warning.get("breathingStop") == null) {
            warning.put("breathingStop", 0);
        }
        if (warning.get("heartbeatFast") == null) {
            warning.put("heartbeatFast", 0);
        }
        if (warning.get("heartbeatSlow") == null) {
            warning.put("heartbeatSlow", 0);
        }
        result.put("warning", warning);
    }

    public void setBreathingData(Map<String, Integer> items, TBedHealthDailyStatisticsData d) {
        if (d.getAhi() != null && d.getAhi() != 0) {
            if (d.getAhi() >= 5 && d.getAhi() < 15) {
                Integer low = items.get("low");
                items.put("low", low == null ? 1 : low + 1);
            } else if (d.getAhi() >= 15 && d.getAhi() < 30) {
                Integer middle = items.get("middle");
                items.put("middle", middle == null ? 1 : middle + 1);
            } else if (d.getAhi() >= 30) {
                Integer high = items.get("high");
                items.put("high", high == null ? 1 : high + 1);
            }
        }
    }

    public void setSleepData(Map<String, Integer> items, TBedHealthDailyStatisticsData d) {
        if (d.getScore() != null) {
            if (d.getScore() < 60) {
                Integer low = items.get("low");
                items.put("low", low == null ? 1 : low + 1);
            } else if (d.getScore() >= 60 && d.getScore() < 85) {
                Integer middle = items.get("middle");
                items.put("middle", middle == null ? 1 : middle + 1);
            } else {
                Integer high = items.get("high");
                items.put("high", high == null ? 1 : high + 1);
            }
        } else {
            items.put("low", 0);
            items.put("middle", 0);
            items.put("high", 0);
        }

    }

    public List<TBedHealthDailyStatisticsData> getSleepTopList(LocalDate localDate, List<Integer> deanAllUser, String orderByColumnName,Map<Integer, RadarBedVo> radarBedVoMap) {
        List<TBedHealthDailyStatisticsData> topList = tBedHealthDailyStatisticsDataMapper.getTop(localDate, deanAllUser, orderByColumnName);
        topList.forEach(t -> {
            t.setBedName(bedService.getBedName(t.getBedId()));
            if (t.getScore() == null) {
                t.setScore(0.0);
            }
            //同比上一期
            LocalDate nextLocalDate = localDate.minusDays(1);
            List<TBedHealthDailyStatisticsData> nextTop = tBedHealthDailyStatisticsDataMapper.getTop(nextLocalDate, Lists.newArrayList(t.getBedId()), orderByColumnName);
            if (nextTop != null && nextTop.size() > 0) {
                TBedHealthDailyStatisticsData statisticsData = nextTop.get(0);
                if (t.getScore() != null && statisticsData != null && statisticsData.getScore() != null) {
                    if (t.getScore() > statisticsData.getScore()) {
                        t.setIsRise(1);
                    } else if (t.getScore() < statisticsData.getScore()) {
                        t.setIsRise(-1);
                    } else {
                        t.setIsRise(0);
                    }
                } else {
                    t.setIsRise(0);
                }
            } else {
                t.setIsRise(0);
            }
            if(radarBedVoMap.containsKey(t.getBedId())){
                t.setSn(radarBedVoMap.get(t.getBedId()).getSnCode());
            }
        });
        return topList;
    }

    public List<TBedHealthDailyStatisticsData> getAhiTopList(LocalDate localDate, List<Integer> deanAllUser, String orderByColumnName,Map<Integer, RadarBedVo> radarBedVoMap) {
        List<TBedHealthDailyStatisticsData> topList = tBedHealthDailyStatisticsDataMapper.getTop(localDate, deanAllUser, orderByColumnName);
        topList.forEach(t -> {
            t.setBedName(bedService.getBedName(t.getBedId()));
            if (t.getAhi() == null) {
                t.setAhi(0.0);
            }
            //同比上一期
            LocalDate nextLocalDate = localDate.minusDays(1);
            List<TBedHealthDailyStatisticsData> nextTop = tBedHealthDailyStatisticsDataMapper.getTop(nextLocalDate, Lists.newArrayList(t.getBedId()), orderByColumnName);
            if (nextTop != null && nextTop.size() > 0) {
                TBedHealthDailyStatisticsData statisticsData = nextTop.get(0);
                if (t.getAhi() != null && statisticsData != null && statisticsData.getAhi() != null) {
                    if (t.getAhi() > statisticsData.getAhi()) {
                        t.setIsRise(1);
                    } else if (t.getAhi() < statisticsData.getAhi()) {
                        t.setIsRise(-1);
                    } else {
                        t.setIsRise(0);
                    }
                } else {
                    t.setIsRise(0);
                }
            } else {
                t.setIsRise(0);
            }
            if(radarBedVoMap.containsKey(t.getBedId())){
                t.setSn(radarBedVoMap.get(t.getBedId()).getSnCode());
            }
        });
        return topList;
    }


    public List<TBedHealthDailyStatisticsData> getFallTopList(LocalDate localDate, List<Integer> deanAllUser, String orderByColumnName,Map<Integer, RadarBedVo> radarBedVoMap) {
        List<TBedHealthDailyStatisticsData> topList = tBedHealthDailyStatisticsDataMapper.getTop(localDate, deanAllUser, orderByColumnName);
        topList.removeIf(t -> {
            if (t.getFallIndex() == null || t.getFallIndex() == 0) {
                return true;
            }
            return false;
        });
        topList.forEach(t -> {
            t.setBedName(bedService.getBedName(t.getBedId()));
            if (t.getFallIndex() == null) {
                t.setFallIndex(0);
            }
            //同比上一期
            LocalDate nextLocalDate = localDate.minusDays(1);
            List<TBedHealthDailyStatisticsData> nextTop = tBedHealthDailyStatisticsDataMapper.getTop(nextLocalDate, Lists.newArrayList(t.getBedId()), orderByColumnName);
            if (nextTop != null && nextTop.size() > 0) {
                TBedHealthDailyStatisticsData statisticsData = nextTop.get(0);
                if (t.getFallIndex() != null && statisticsData != null && statisticsData.getFallIndex() != null) {
                    if (t.getFallIndex() > statisticsData.getFallIndex()) {
                        t.setIsRise(1);
                    } else if (t.getFallIndex() < statisticsData.getFallIndex()) {
                        t.setIsRise(-1);
                    } else {
                        t.setIsRise(0);
                    }
                } else {
                    t.setIsRise(0);
                }
            } else {
                t.setIsRise(0);
            }
            if(radarBedVoMap.containsKey(t.getBedId())){
                t.setSn(radarBedVoMap.get(t.getBedId()).getSnCode());
            }
        });
        return topList;
    }

    public List<TBedHealthDailyStatisticsData> getMoraleTopList(LocalDate localDate, List<Integer> deanAllUser, String orderByColumnName,Map<Integer, RadarBedVo> radarBedVoMap) {
        List<TBedHealthDailyStatisticsData> topList = tBedHealthDailyStatisticsDataMapper.getTop(localDate, deanAllUser, orderByColumnName);
        topList.removeIf(t -> {
            if (t.getMoraleIndex() == null || t.getMoraleIndex() == 0) {
                return true;
            }
            return false;
        });
        topList.forEach(t -> {
            t.setBedName(bedService.getBedName(t.getBedId()));
            if (t.getMoraleIndex() == null) {
                t.setMoraleIndex(0);
            }
            //同比上一期
            LocalDate nextLocalDate = localDate.minusDays(1);
            List<TBedHealthDailyStatisticsData> sleepTop = tBedHealthDailyStatisticsDataMapper.getTop(nextLocalDate, Lists.newArrayList(t.getBedId()), orderByColumnName);
            if (sleepTop != null && sleepTop.size() > 0) {
                TBedHealthDailyStatisticsData statisticsData = sleepTop.get(0);
                if (t.getMoraleIndex() != null && statisticsData != null && statisticsData.getMoraleIndex() != null) {
                    if (t.getMoraleIndex() > statisticsData.getMoraleIndex()) {
                        t.setIsRise(1);
                    } else if (t.getMoraleIndex() < statisticsData.getMoraleIndex()) {
                        t.setIsRise(-1);
                    } else {
                        t.setIsRise(0);
                    }
                } else {
                    t.setIsRise(0);
                }
            } else {
                t.setIsRise(0);
            }
            if(radarBedVoMap.containsKey(t.getBedId())){
                t.setSn(radarBedVoMap.get(t.getBedId()).getSnCode());
            }
        });
        return topList;
    }

    public List<TBedHealthDailyStatisticsData> getVitalityTopList(LocalDate localDate, List<Integer> deanAllUser, String orderByColumnName,Map<Integer, RadarBedVo> radarBedVoMap) {
        List<TBedHealthDailyStatisticsData> topList = tBedHealthDailyStatisticsDataMapper.getTop(localDate, deanAllUser, orderByColumnName);
        topList.removeIf(t -> {
            if (t.getVitalityIndex() == null || t.getVitalityIndex() == 0) {
                return true;
            }
            return false;
        });
        topList.forEach(t -> {
            t.setBedName(bedService.getBedName(t.getBedId()));
            if (t.getVitalityIndex() == null) {
                t.setVitalityIndex(0);
            }
            //同比上一期
            LocalDate nextLocalDate = localDate.minusDays(1);
            List<TBedHealthDailyStatisticsData> sleepTop = tBedHealthDailyStatisticsDataMapper.getTop(nextLocalDate, Lists.newArrayList(t.getBedId()), orderByColumnName);
            if (sleepTop != null && sleepTop.size() > 0) {
                TBedHealthDailyStatisticsData statisticsData = sleepTop.get(0);
                if (t.getVitalityIndex() != null && statisticsData != null && statisticsData.getVitalityIndex() != null) {
                    if (t.getVitalityIndex() > statisticsData.getVitalityIndex()) {
                        t.setIsRise(1);
                    } else if (t.getVitalityIndex() < statisticsData.getVitalityIndex()) {
                        t.setIsRise(-1);
                    } else {
                        t.setIsRise(0);
                    }
                } else {
                    t.setIsRise(0);
                }
            } else {
                t.setIsRise(0);
            }
            if(radarBedVoMap.containsKey(t.getBedId())){
                t.setSn(radarBedVoMap.get(t.getBedId()).getSnCode());
            }
        });
        return topList;
    }




    /**
     * 获取院长名下所有床位号
     *
     * @param user
     * @return
     */
    public List<Integer> getBeanAllByUser(User user, String startDate, String endDate) {
        Set<Integer> result = new HashSet<>();
        if (user.getRoleId().equals(String.valueOf(RoleEnum.WARDEN.getCode()))) {
            List<DeanBed> deanBeds = deanBedMapper.selectByUserAndType(user.getId(), startDate, endDate);
            if (CollectionUtils.isNotEmpty(deanBeds)) {
                deanBeds.forEach(d -> {
                    switch (d.getType()) {
                        case 1:
                            if (isBed(d.getObjId())) {
                                result.add(d.getObjId());
                            }
                            break;
                        case 2:
                            CommonRes<List<Bed>> bedByRoomId = bedService.getBedByRoomId(d.getObjId());
                            List<Bed> data = bedByRoomId.getData();
                            if (CollectionUtils.isNotEmpty(data)) {
                                data.forEach(b -> {
                                    if (isBed(b.getId())) {
                                        result.add(b.getId());
                                    }

                                });
                            }
                            ;
                            break;
                        case 3:
                            List<Bed> bedByFloorId = bedService.getBedByFloorId(d.getObjId());
                            if (CollectionUtils.isNotEmpty(bedByFloorId)) {
                                bedByFloorId.forEach(f -> {
                                    if (isBed(f.getId())) {
                                        result.add(f.getId());
                                    }
                                });
                            }
                            ;
                            break;
                        case 4:
                            List<Bed> bedByBuildingId = bedService.getBedByBuildingId(d.getObjId());
                            if (CollectionUtils.isNotEmpty(bedByBuildingId)) {
                                bedByBuildingId.forEach(f -> {
                                    if (isBed(f.getId())) {
                                        result.add(f.getId());
                                    }
                                });
                            }
                            ;
                            break;
                        case 5:
                            QueryWrapper queryWrapper = new QueryWrapper();
                            queryWrapper.eq("tenant_id", user.getTenantId());
                            queryWrapper.eq("is_deleted", 0);
                            List<Bed> bedAll = bedService.list(queryWrapper);
                            if (CollectionUtils.isNotEmpty(bedAll)) {
                                bedAll.forEach(f -> {
                                    if (isBed(f.getId())) {
                                        result.add(f.getId());
                                    }
                                });
                            }
                            break;
                        default:
                            //result.add(d.getObjId());
                    }
                });
            }
        }
        System.out.println(result);
        List<Integer> resultList = new ArrayList<>();
        resultList.addAll(result);
        return resultList;
    }


    /**
     * 获取院长名下所有床位号包括卫生间
     *
     * @param user
     * @return
     */
    public List<Integer> getBeanAllByUserV1(User user, String startDate, String endDate) {
        Set<Integer> result = new HashSet<>();
        if (user.getRoleId().equals(String.valueOf(RoleEnum.WARDEN.getCode()))) {
            List<DeanBed> deanBeds = deanBedMapper.selectByUserAndType(user.getId(), startDate, endDate);
            if (CollectionUtils.isNotEmpty(deanBeds)) {
                deanBeds.forEach(d -> {
                    switch (d.getType()) {
                        case 1:
                            if (isBedV1(d.getObjId())) {
                                result.add(d.getObjId());
                            }
                            break;
                        case 2:
                            CommonRes<List<Bed>> bedByRoomId = bedService.getBedByRoomId(d.getObjId());
                            List<Bed> data = bedByRoomId.getData();
                            if (CollectionUtils.isNotEmpty(data)) {
                                data.forEach(b -> {
                                    if (isBedV1(b.getId())) {
                                        result.add(b.getId());
                                    }

                                });
                            }
                            ;
                            break;
                        case 3:
                            List<Bed> bedByFloorId = bedService.getBedByFloorId(d.getObjId());
                            if (CollectionUtils.isNotEmpty(bedByFloorId)) {
                                bedByFloorId.forEach(f -> {
                                    if (isBedV1(f.getId())) {
                                        result.add(f.getId());
                                    }
                                });
                            }
                            ;
                            break;
                        case 4:
                            List<Bed> bedByBuildingId = bedService.getBedByBuildingId(d.getObjId());
                            if (CollectionUtils.isNotEmpty(bedByBuildingId)) {
                                bedByBuildingId.forEach(f -> {
                                    if (isBedV1(f.getId())) {
                                        result.add(f.getId());
                                    }
                                });
                            }
                            ;
                            break;
                        case 5:
                            QueryWrapper queryWrapper = new QueryWrapper();
                            queryWrapper.eq("tenant_id", user.getTenantId());
                            queryWrapper.eq("is_deleted", 0);
                            List<Bed> bedAll = bedService.list(queryWrapper);
                            if (CollectionUtils.isNotEmpty(bedAll)) {
                                bedAll.forEach(f -> {
                                    if (isBedV1(f.getId())) {
                                        result.add(f.getId());
                                    }
                                });
                            }
                            break;
                        default:
                            result.add(d.getObjId());
                    }
                });
            }
        }
        List<Integer> resultList = new ArrayList<>();
        resultList.addAll(result);
        return resultList;

    }
    private boolean isBed(Integer bedId) {
        return bedService.isBed(bedId);
    }
    private boolean isBedV1(Integer bedId) {
        return bedService.isBedV1(bedId);
    }

}
